from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.status import HTTP_201_CREATED, HTTP_404_NOT_FOUND, HTTP_204_NO_CONTENT

from study.models import Student, Classes
from study.serializers import StudentSerializer, ClassesSerializer

'''
class StudentViewSet(viewsets.ViewSet):
    def list(self, request):
        queryset = Student.objects.all()
        # 序列化，实例化序列化器，将查询集转为json格式数据
        serializer = StudentSerializer(queryset, many=True)
        return Response(serializer.data)

    def create(self, request):  # 1.获取前端传入的数据，2.反序列化，3.校验，4.保存数据，5.返回响应
        data = request.data
        # 反序列化
        serializer = StudentSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=HTTP_201_CREATED)

    def retrieve(self, request, pk):  # 1.根据pk查询对象，如果有序列化对象，如果没有抛出错误，2.返回响应
        try:
            student = Student.objects.get(id=pk)
        except Student.DoesNotExist:
            return Response(status=HTTP_404_NOT_FOUND)

        serializer = StudentSerializer(instance=student)
        return Response(serializer.data)

    # 1.根据pk查询对象，如果有序列化对象，如果没有抛出错误，2.获取前端传入的数据，3.反序列化，4.校验，5.保存数据，6.返回响应
    def update(self, request, pk):
        try:
            student = Student.objects.get(id=pk)
        except Student.DoesNotExist:
            return Response(status=HTTP_404_NOT_FOUND)

        serializer = StudentSerializer(instance=student, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=HTTP_201_CREATED)

    def destroy(self, request, pk):
        try:
            student = Student.objects.get(id=pk)
        except Student.DoesNotExist:
            return Response(status=HTTP_404_NOT_FOUND)

        student.delete()  # 直接调用delete方法会把后台数据也直接删除
        return Response(status=HTTP_204_NO_CONTENT)
'''


class StudentViewSet(viewsets.ModelViewSet):
    queryset = Student.objects.filter(is_delete=False)
    serializer_class = StudentSerializer


class ClassesViewSet(viewsets.ModelViewSet):
    """
    list:查看全部班级信息
    create:新增班级信息
    retrieve:查看某个班级信息
    update:修改某个班级信息
    destroy:删除某个班级信息
    last:查看最新班级信息
    """
    queryset = Classes.objects.filter(is_delete=False)
    serializer_class = ClassesSerializer

    @action(methods=['get'], detail=False)  # action装饰器，用于在页面增加接口，如果detail=True，下面last函数要带参数pk
    def last(self, request):
        last_class = Classes.objects.filter(is_delete=False).last()
        serializer = self.get_serializer(last_class)  # 序列化
        return Response(serializer.data)
